layui.use(['routers', 'conf', 'utils', 'bodyTab', 'form', 'authServices', 'greyServices', 'mandyServices', 'store', 'menu',],
    function (routers, config, utils, bodyTab, form, authServices, greyServices, mandyServices, store, menu) {
        //全局对象
        ARES = utils.ARES;

        /**
         * @author: ares
         * @date: 2020/2/18 9:59
         * @description: 判断运行环境是否是服务器环境
         */
        if (!/http(s*):\/\//.test(location.href)) utils.alert("请先将项目部署到服务器环境下，否则部分功能或数据会出现异常!");

        /*utils.ARES.webSocket.onopen = function(event){
            console.log('websocket链接')
            //socket.send('websocket client connect test');
        }
        utils.ARES.webSocket.onclose = function(event){
            console.log('websocket服务器断开连接');
        }
        utils.ARES.webSocket.onerror = function(event){
            console.log('websocket发生错误')
        }*/

        //系统右下角固定块,返回顶部操作
        utils.fixbar({scrollDom: '.layui-body'});

        //先查下缓存中的openedTabs,不然刷新页面会被冲掉
        var sessionTabs = store.session.get('openedTabs') || [],
            sessionStorageLockScreen = !!store.session.get("lockScreen"),
            sessionStorageDisplayedNotice = !!store.session.get("displayedNotice");

        /**
         * @author: ares
         * @date: 2020/2/18 10:56
         * @description: 是否锁屏
         */
        if (sessionStorageLockScreen) lockScreen();

        /**
         * @author: ares
         * @date: 2020/2/18 10:56
         * @description: 是否显示系统通知
         */

        // if (!sessionStorageLockScreen && !sessionStorageDisplayedNotice) showNotice();

        /**
         * @author: ares
         * @date: 2021/1/27 11:23
         * @description: 重置iframe高度
         */
        function resetContentIframeHeight() {
            setInterval(function () {
                var iframe = $('#sys-tabs-content>.layui-tab-item.layui-show>iframe');
                if (iframe.length && iframe[0].contentDocument && iframe[0].contentDocument.body) iframe[0].height = iframe[0].contentDocument.body.scrollHeight + 'px';
            }, 500)
        }

        /**
         * @author: ares
         * @date: 2021/1/19 16:22
         * @description: 获取登录用户个人信息
         */
        function getProfile() {
            return greyServices.grey_get_profile().then(function (res) {
                var profile = res.data;
                if (!profile) return;
                store.set('profile', profile);
                store.session.set('job', profile.job);
                store.session.set('profileId', profile.id);
                if (profile.institution) {
                    store.session.set('hospital', profile.institution.hospital.id);
                    store.session.set('division', profile.institution.division.id);
                    store.session.set('roleId', profile.institution.role.id);
                }
                profile.head && $(".user-avatar").attr("src", profile.head);
                $(".admin-name").text('您好! ' + profile.name);
                setSysHosDivName(profile.institution.hospital.name, profile.institution.division.name);
                return res.data;
            })
        }

        /**
         * @author: ares
         * @date: 2020/1/31 13:59
         * @description: 锁定页面
         */
        function lockScreen() {
            var profile = store.get('profile');
            if (!profile) {
                utils.message('系统初始化中...')
                return;
            }
            var content = '<div id="lock-screen-box">' +
                '<div class="lock-screen-img"><img src="images/logo.png"/></div>' +
                '<div class="lock-screen-name" id="lock-user-name">' + profile.name + '</div>' +
                '<div>' +
                '<input type="password" class="lock-screen-input layui-input" autocomplete="off" placeholder="请输入密码解锁.."/>' +
                '<button class="layui-btn unlock">解锁</button>' +
                '</div>' +
                '</div>';
            utils.layerOpen({
                title: false,
                type: 1,
                content: content,
                closeBtn: 0,
                shade: 0.8,
                success: function () {
                    $("#lock-screen-box .lock-screen-input").focus();
                }
            })
        }

        /**
         * @author: ares
         * @date: 2020/1/31 13:42
         * @description: 显示系统公告
         */
        function showNotice() {
            var content = '<div style="padding:15px 20px; line-height: 22px; text-indent:2em;border-bottom:1px solid #e2e2e2;">' +
                '<p>公告内容</p>' +
                '</div>';
            utils.layerOpen({
                type: 1,
                title: "系统公告",
                area: '300px',
                shade: 0.8,
                id: 'LAY_notice',
                btn: ['确认'],
                btnAlign: 'c',
                content: content,
                yes: function (index, layero) {
                    utils.layer.close(index)
                    showNoticeTip();
                    store.session.set("displayedNotice", 1);
                },
                cancel: function (index, layero) {
                    showNoticeTip();
                }
            });
        }

        /**
         * @author: ares
         * @date: 2020/1/31 15:25
         * @description: 关闭公告时提示公告按钮位置
         */
        function showNoticeTip() {
            if ($(window).width() > 432) {  //如果页面宽度不足以显示顶部“系统公告”按钮，则不提示
                utils.layerTips('系统公告躲在了这里', '#user-info', {
                    tips: 3,
                    time: 1000
                });
            }
        }

        /**
         * @author: ares
         * @date: 2020/1/31 14:27
         * @description: 显示更换主题模态框
         */
        function showChangeTheme() {
            var content = '<div id="theme-box">' +
                '<form class="layui-form">' +
                '<div class="layui-form-item">' +
                '<input type="radio" name="theme" value="default" title="默认" lay-filter="default" checked="">' +
                '<input type="radio" name="theme" value="orange" title="橙色" lay-filter="orange">' +
                '<input type="radio" name="theme" value="blue" title="蓝色" lay-filter="blue">' +
                '<input type="radio" name="theme" value="custom" title="自定义" lay-filter="custom">' +
                '</div>' +
                '<div class="theme-custom" style="display:none;">' +
                '<input type="text" class="layui-input top-color" placeholder="顶部颜色" />' +
                '<input type="text" class="layui-input left-color" placeholder="左侧颜色" />' +
                '<input type="text" class="layui-input menu-color" placeholder="顶部菜单按钮" />' +
                '</div>' +
                '</form>' +
                '</div>';
            utils.layerOpen({
                title: "更换主题",
                area: ["310px", "300px"],
                type: "1",
                btn: ['确认', '放弃'],
                btnAlign: 'c',
                content: content,
                yes: function (index, layero) {
                    var themeType = layero.find("input:checked").val(),
                        topColor = layero.find(".top-color").val(),
                        leftColor = layero.find(".left-color").val(),
                        menuColor = layero.find(".menu-color").val(),
                        theme = '';
                    if (themeType == "custom") {
                        theme = topColor + ',' + leftColor + ',' + menuColor;
                        store.session.set("customTheme", 1);
                    } else {
                        theme = themeType;
                        if (theme == 'default') theme = '';
                        store.session.remove("customTheme");
                    }
                    if (theme) {
                        store.session.set("theme", theme);
                    } else {
                        store.session.remove("theme");
                    }
                    updateTheme()
                    utils.layer.close(index)
                },
                btn2: function (index, layero) {
                    $(".layui-layout-body").removeAttr("class").addClass("layui-layout-body");
                    $(".layui-bg-black,.toggle-menu,.layui-layout-admin .layui-header").removeAttr("style");
                    updateTheme()
                    utils.layer.close(index)
                },
                success: function (layero, index) {
                    var theme = store.session.get("theme"),
                        isCustomTheme = store.session.get("customTheme");
                    if (!theme) theme = 'default';
                    if (isCustomTheme) {
                        layero.find("input[value=custom]").attr("checked", "checked");
                        layero.find(".theme-custom").show();
                        layero.find(".top-color").val(theme.split(',')[0]);
                        layero.find(".left-color").val(theme.split(',')[1]);
                        layero.find(".menu-color").val(theme.split(',')[2]);
                    } else {
                        layero.find("input[value=" + theme + "]").attr("checked", "checked");
                    }

                    layero.on("click", ".layui-form-radio", function () {
                        var val = $(this).prev().val();
                        if (val == 'custom') {
                            layero.find(".theme-custom").show();
                        } else {
                            $(".layui-layout-body").removeAttr("class").addClass("layui-layout-body " + val + "");
                            $(".layui-bg-black,.toggle-menu,.layui-layout-admin .layui-header").removeAttr("style");
                            layero.find(".theme-custom").hide();
                            layero.find(".top-color,.left-color,.menu-color").val('');
                        }
                    })
                    layero.find(".top-color").on('blur', function () {
                        var color = $(this).val() ? 'background-color:' + $(this).val() + ' !important' : '';
                        if (!color) return;
                        $(".layui-layout-admin .layui-header")[0].setAttribute('style', color);
                    })
                    layero.find(".left-color").on('blur', function () {
                        var color = $(this).val() ? 'background-color:' + $(this).val() + ' !important' : '';
                        if (!color) return;
                        $(".layui-bg-black")[0].setAttribute('style', color);
                    })
                    layero.find(".menu-color").on('blur', function () {
                        var color = $(this).val() ? 'background-color:' + $(this).val() + ' !important' : '';
                        if (!color) return;
                        $(".toggle-menu")[0].setAttribute('style', color);
                    })
                    form.render();
                },
                cancel: function () {
                    $(".layui-layout-body").removeAttr("class").addClass("layui-layout-body");
                    $(".layui-bg-black,.toggle-menu,.layui-layout-admin .layui-header").removeAttr("style");
                    updateTheme()
                }
            })
        }

        /**
         * @author: ares
         * @date: 2020/1/31 14:23
         * @description: 更新主题
         */
        function updateTheme() {
            var theme = store.session.get("theme");
            if (theme) {
                if (store.session.get("customTheme")) {
                    $(".layui-layout-admin .layui-header")[0].setAttribute('style', "background-color:" + theme.split(',')[0] + '!important');
                    $(".layui-bg-black")[0].setAttribute('style', "background-color:" + theme.split(',')[1] + '!important');
                    $(".toggle-menu")[0].setAttribute('style', "background-color:" + theme.split(',')[2] + '!important');
                } else {
                    $(".layui-layout-body").addClass(store.session.get("theme"));
                }
            }
        }

        /**
         * @author: ares
         * @date: 2020/2/1 12:36
         * @description: 全屏
         */
        function fullScreen() {
            var el = document.documentElement,
                rfs = el.requestFullScreen || el.webkitRequestFullScreen;
            if (typeof rfs != "undefined" && rfs) {
                rfs.call(el);
            } else if (typeof window.ActiveXObject != "undefined") {
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript != null) {
                    wscript.SendKeys("{F11}");
                }
            } else if (el.msRequestFullscreen) {
                el.msRequestFullscreen();
            } else if (el.oRequestFullscreen) {
                el.oRequestFullscreen();
            } else {
                utils.msgError('浏览器不支持全屏调用！');
            }
        }

        /**
         * @author: ares
         * @date: 2020/2/1 12:42
         * @description: 退出全屏
         */
        function exitFullScreen() {
            var el = document,
                cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.exitFullScreen;
            if (typeof cfs != "undefined" && cfs) {
                cfs.call(el);
            } else if (typeof window.ActiveXObject != "undefined") {
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript != null) {
                    wscript.SendKeys("{F11}");
                }
            } else if (el.msExitFullscreen) {
                el.msExitFullscreen();
            } else if (el.oRequestFullscreen) {
                el.oCancelFullScreen();
            } else {
                utils.msgError('浏览器不支持全屏调用！');
            }
        }

        /**
         * @author: ares
         * @date: 2020/2/14 17:42
         * @description: 配置系统名称和所在医院名称
         * @param{string} hospitalName 医院名称
         * @param{string} divisionName 科室名称
         */
        function setSysHosDivName(hospitalName, divisionName) {
            $(".app-system-name").length && $(".app-system-name").text(config.systemName);
            $(".app-system-hospital-name").length && $(".app-system-hospital-name").text(hospitalName + '—' + divisionName);
        }

        /**
         * @author: ares
         * @date: 2020/12/26 14:07
         * @description: 初始化系统面包屑导航
         */
        function initSysBreadcrumb() {
            var $sysBreadcrumb = $('#sys-breadcrumb'),
                $homePage = $('<li><a href="#' + config.homePagePath + '">' + config.homePageTitle + '</a></li>');
            $sysBreadcrumb.empty().append($homePage);
        }

        /**
         * @author: ares
         * @date: 2020/12/26 14:08
         * @description: 初始化系统tab
         */
        function initSysTabs() {
            var $sysTabs = $('#sys-tabs'),
                $homepageTab = $('<li lay-id="' + config.homePagePath + '" class="homepage-tab layui-this">' +
                    '<a href="#' + config.homePagePath + '">' +
                    '<i class="tab-icon ' + config.homePageIcon + '"></i>' +
                    '<cite class="tab-title" data-file="' + config.homePageFilePath + '">' + config.homePageTitle + '</cite>' +
                    '</a>' +
                    '</li>');
            $sysTabs.empty().append($homepageTab);
        }

        /**
         * @author: ares
         * @date: 2020/12/26 14:57
         * @description: 初始化系统tabcontent
         */
        function initSysTabsContent() {
            var $sysTabsContent = $('#sys-tabs-content'),
                $homepageTabContent = $('<div class="layui-tab-item homepage-tab-item layui-show"></div>');
            utils.loadIframeView(config.homePageFilePath, $homepageTabContent, function cb() {
                $sysTabsContent.empty().append($homepageTabContent);
                bodyTab.loadSessionTabs(sessionTabs);
                //重新缓存一下,不然会被冲掉
                store.session.set('openedTabs', sessionTabs);
            })
        }

        /**
         * @author: ares
         * @date: 2020/2/15 21:56
         * @description: 设置版权
         */
        function setCopyRight() {
            var currentYear = new Date().getFullYear(),
                copyright = config.copyright + currentYear + config.author;
            $('#copyright').length && $('#copyright').text(copyright)
        }

        /**
         * @author: ares
         * @date: 2021/4/14 11:19
         * @description: 更新未读消息数
         */
        function updateNewMessageCount() {
            setInterval(function () {
                mandyServices.mandy_get_my_message_unread_count().then(function (res) {
                    $('#new-msg-count').text(res.data.count);
                })
            }, 5*60000)
        }

        /**
         * @author: ares
         * @date: 2020/1/28 17:03
         * @description: toggle menu
         */
        $(".toggle-menu").on('click', function () {
            $(".layui-layout-admin").toggleClass("hide-menu");
        })

        /**
         * @author: ares
         * @date: 2020/1/28 17:26
         * @description: 移动端toggle menu
         */
        $('.site-tree-mobile').on('click', function () {
            $('.layui-layout-body').addClass('site-mobile');
        });
        $('.site-mobile-shade').on('click', function () {
            $('.layui-layout-body').removeClass('site-mobile');
        });

        /**
         * @author: ares
         * @date: 2020/1/29 19:53
         * @description: 绑定清除缓存事件
         */
        $(".header-menus-right .clear-cache").on('click', function () {
            store.session.remove('openedTabs');
            var index = utils.layerLoadingMsg('清除缓存中，请稍候');
            setTimeout(function () {
                utils.layerClose(index);
                utils.message("缓存清除成功！");
                location.reload()
            }, 1000);
        })
        /**
         * @author: ares
         * @date: 2020/1/31 13:58
         * @description: 绑定锁屏事件
         */
        $(".header-menus-right .lock-screen").on("click", function () {
            lockScreen();
            store.session.set("lockScreen", 1);
        })

        /**
         * @author: ares
         * @date: 2020/1/31 14:02
         * @description: 解锁页面
         */
        $(".layui-layout-body").on("click", "#lock-screen-box .unlock", function () {
            var profile = store.get('profile'),
                $unlockInput = $("#lock-screen-box .lock-screen-input");
            if ($unlockInput.val() == '') {
                utils.msgWarning("请输入解锁密码！");
                $unlockInput.focus();
            } else {
                if ($unlockInput.val() == profile.birthday.replace(/-/g, '')) {
                    $unlockInput.val('');
                    utils.layer.closeAll("page");
                    store.session.remove("lockScreen");
                } else {
                    utils.msgWarning("密码错误，请重新输入！");
                    $unlockInput.val('').focus();
                }
            }
        });

        /**
         * @author: ares
         * @date: 2020/1/31 14:05
         * @description: 回车键解锁
         */
        $(document).on('keydown', function (event) {
            var event = event || window.event;
            if (event.keyCode == 13) {
                $("#lock-screen-box .unlock").length && $("#lock-screen-box .unlock").trigger('click');
            }
        });

        /**
         * @author: ares
         * @date: 2020/2/1 13:05
         * @description: toggle full screen
         */
        $(".header-menus-right .toggle-full-screen").on("click", function () {
            if ($(this).hasClass('full')) {
                exitFullScreen()
            } else {
                fullScreen()
            }
            $(this).toggleClass('full')
        })

        /**
         * @author: ares
         * @date: 2020/1/31 13:56
         * @description: 绑定显示公告事件
         */
        $("#user-info .show-notice").on("click", function () {
            showNotice();
        })

        /**
         * @author: ares
         * @date: 2020/1/31 14:15
         * @description: 绑定更换皮肤事件
         */
        $("#user-info .change-theme").on('click', function () {
            showChangeTheme()
        })

        /**
         * @author: ares
         * @date: 2020/1/31 14:08
         * @description: 退出登录
         */
        $("#user-info .sign-out").on('click', function () {
            authServices.logout()
        })


        /**
         * @author: ares
         * @date: 2020/12/26 14:08
         * @description: 系统初始化
         */
        function init() {
            var loading = utils.layerLoadingMsg('系统初始化中...');
            initSysBreadcrumb();
            initSysTabs();
            initSysTabsContent();
            setCopyRight();
            updateTheme();
            resetContentIframeHeight();
            updateNewMessageCount();
            utils.updateBreadcrumb(routers);
            getProfile().then(function (profile) {
                menu.getSideMenu().then(function (menus) {
                    utils.layerClose(loading);
                    utils.highLightAside();
                })
            })
        }

        init();
    })